<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/6/19
 * Time: 14:31
 */

namespace iBrand\Shop\Core\Models;


use iBrand\Component\Purchase\Models\TakeStock;
use Illuminate\Database\Eloquent\Model;

class TakeStockPlan extends Model
{
    protected $guarded = ['id'];

    protected $appends = ['profit_count', 'profit_amount', 'take_total'];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $prefix = config('ibrand.app.database.prefix', 'ibrand_');

        $this->setTable($prefix . 'store_take_plan');
    }

    public function items()
    {
        return $this->hasMany(TakeStockPlanItems::class);
    }

    public function takeStocks()
    {
        return $this->hasMany(TakeStock::class, 'plan_id');
    }

    /**
     * 盈亏数量
     * @return int
     */
    public function getProfitCountAttribute()
    {
        if ($this->takeStocks->count()) {
            return $this->takeStocks->sum('difference_count');
        }
        return 0;
    }

    /**
     * 盈亏金额
     * @return int
     */
    public function getProfitAmountAttribute()
    {
        if ($this->takeStocks->count()) {
            return $this->takeStocks->sum('difference_amount');
        }
        return 0;
    }

    /**
     * 盘点总数量
     * @return int
     */
    public function getTakeTotalAttribute()
    {
        if ($this->takeStocks->count()) {
            return $this->takeStocks->sum('total');
        }
        return 0;
    }


}